package com.itany.springcloud.consumer.controller;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.itany.springcloud.common.entity.User;
import com.itany.springcloud.common.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;
    private static final String GLOBAL_URL="http://127.0.0.1:8080/users";

    @PostMapping
    public ResponseResult add(User user){
        MultiValueMap params=new LinkedMultiValueMap();
        params.add("username",user.getUsername());
        params.add("password",user.getPassword());
        return restTemplate.postForObject(GLOBAL_URL,params,ResponseResult.class);
    }

    @GetMapping
    public ResponseResult findAll(){
        return restTemplate.getForObject(GLOBAL_URL,ResponseResult.class);
    }

    @GetMapping("/{id}")
    public ResponseResult findById(@PathVariable("id") Integer id){
        return restTemplate.getForObject(GLOBAL_URL+"/{id}",ResponseResult.class,id);
    }

    @DeleteMapping("/{id}")
    public ResponseResult remove(@PathVariable("id") Integer id){
        restTemplate.delete(GLOBAL_URL+"/{id}",id);
        return ResponseResult.success();
    }

    @PutMapping
    public ResponseResult modify(User user){
        MultiValueMap params=new LinkedMultiValueMap();
        params.add("id",user.getId());
        params.add("username",user.getUsername());
        params.add("password",user.getPassword());
        restTemplate.put(GLOBAL_URL,params);
        return ResponseResult.success();

//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Content-Type",MediaType.MULTIPART_FORM_DATA_VALUE);
//        MultiValueMap params=new LinkedMultiValueMap();
//        params.add("id",user.getId());
//        params.add("username",user.getUsername());
//        params.add("password",user.getPassword());
//        HttpEntity< MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
//        ResponseEntity<ResponseResult> responseEntity=restTemplate.exchange(GLOBAL_URL, HttpMethod.PUT, requestEntity, ResponseResult.class);
//        return responseEntity.getBody();


//        String url=new StringBuffer()
//                .append(GLOBAL_URL)
//                .append("?id={id}")
//                .append("&username={username}")
//                .append("&password={password}")
//                .toString();
//        ResponseEntity<ResponseResult> responseEntity=restTemplate.exchange(url, HttpMethod.PUT, null, ResponseResult.class,user.getId(),user.getUsername(),user.getPassword());
//        return responseEntity.getBody();


    }


}
